#!/usr/bin/env Rscript
################################################################################
# @ Author       : Pengdong Yan
# @ Email        : yanpd01@snnu.edu.cn
# @ Encoding     : UTF-8
# @ Language     :
# @ Date         : 2022-03-29 01:21
# @ LastEditTime : 2022-04-08 17:18
# @ Description  :
################################################################################
sig_label <- function(formula, data,
                      test = c(
                          "wilcox_test", "t_test", "dunn_test", "tukey_hsd",
                          "HSD.test", "duncan.test", "LSD.test", "SNK.test"
                      ),
                      p.adjust.method = "none",
                      alpha = 0.05) {
    fm <- formula(formula)
    test <- match.arg(test)
    t0 <- stats::aggregate(fm, data, mean) %>% tibble::column_to_rownames(colnames(.)[1])
    t0_sd <- stats::aggregate(fm, data, sd) %>% tibble::column_to_rownames(colnames(.)[1])
    id <- rownames(t0)
    id_y <- deparse(fm[[2]])
    id_x <- deparse(fm[[3]])
    if (test %in% c("wilcox_test", "t_test", "dunn_test", "tukey_hsd")) {
        test_fun <- eval(parse(text = paste0("rstatix::", test)))
        t1 <-
            test_fun(data, fm, p.adjust.method = p.adjust.method) %>%
            dplyr::select(group1, group2, p.adj)
        t1_mirror <- dplyr::select(t1, group2, group1, p.adj)
        colnames(t1_mirror) <- colnames(t1)
        t3 <- rbind(t1, t1_mirror)
        t4 <- tidyr::pivot_wider(
            t3,
            id_cols = "group1",
            names_from = "group2",
            values_from = "p.adj"
        ) %>%
            tibble::column_to_rownames("group1") %>%
            .[id, id] %>%
            as.matrix()
        diag(t4) <- 1
        df_out <- agricolae::orderPvalue(id, t0[id, ], alpha, t4) %>% .[id, ]
        # colnames(df_out)[1] <- id_y
    } else {
        test_fun <- eval(parse(text = paste0("agricolae::", test)))
        df_out <- test_fun(stats::aov(fm, data), id_x, alpha = alpha)$groups[id, ]
    }
    colnames(df_out)[1] <- "mean"
    t7 <- cbind(df_out, sd = t0_sd[id, ], term = id_y) %>% dplyr::select(4, 1, 3, 2)
    message(
        "Difference test method: ", test,
        "\nAlpha: ", alpha,
        "\nP.adj: ", p.adjust.method
    )
    return(t7)
}



pheat <- function(cor, main = "", adj = "BH", cluster_rows = T, cluster_cols = T, rm_1 = T, ...) {
    tmp_k <- seq(-1, 1, 0.02)
    tmp_col <- colorRampPalette(rev(RColorBrewer::brewer.pal(n = 7, name = "RdYlBu")))(length(tmp_k))
    pheatmap::pheatmap(
        cor$r,
        display_numbers = get_corr_sig(cor$r, cor$p, adj, rm_1 = rm_1),
        breaks = tmp_k,
        color = tmp_col,
        cluster_rows = cluster_rows,
        cluster_cols = cluster_cols,
        main = main,
        ...
    )
}
